/**
 * Copyright (c) 2015-2016, Chill Zhuang 庄骞 (smallchill@163.com).
<<<<<<< HEAD
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
=======
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
>>>>>>> ee68c197221632319ef2fc245f6f843370572799
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.stylefeng.qz.core.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {


    /**
     * 获取YYYY格式
     *
     * @return
     */
    public static String getYear() {
        return formatDate(new Date(), "yyyy");
    }

    /**
     * 获取YYYY格式
     *
     * @return
     */
    public static String getYear(Date date) {
        return formatDate(date, "yyyy");
    }

    /**
     * 获取YYYY-MM-DD格式
     *
     * @return
     */
    public static String getDay() {
        return formatDate(new Date(), "yyyy-MM-dd");
    }

    /**
     * 获取YYYY-MM-DD格式
     *
     * @return
     */
    public static String getDay(Date date) {
        return formatDate(date, "yyyy-MM-dd");
    }

    /**
     * 获取YYYYMMDD格式
     *
     * @return
     */
    public static String getDays() {
        return formatDate(new Date(), "yyyyMMdd");
    }

    /**
     * 获取YYYYMMDD格式
     *
     * @return
     */
    public static String getDays(Date date) {
        return formatDate(date, "yyyyMMdd");
    }

    /**
     * 获取YYYY-MM-DD HH:mm:ss格式
     *
     * @return
     */
    public static String getTime() {
        return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 获取YYYY-MM-DD HH:mm:ss.SSS格式
     *
     * @return
     */
    public static String getMsTime() {
        return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
    }

    /**
     * 获取YYYYMMDDHHmmss格式
     *
     * @return
     */
    public static String getAllTime() {
        return formatDate(new Date(), "yyyyMMddHHmmss");
    }

    /**
     * 获取YYYY-MM-DD HH:mm:ss格式
     *
     * @return
     */
    public static String getTime(Date date) {
        return formatDate(date, "yyyy-MM-dd HH:mm:ss");
    }

    public static String formatDate(Date date, String pattern) {
        String formatDate = null;
        if (StringUtils.isNotBlank(pattern)) {
            formatDate = DateFormatUtils.format(date, pattern);
        } else {
            formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
        }
        return formatDate;
    }

    /**
     * @param s
     * @param e
     * @return boolean
     * @throws
     * @Title: compareDate
     * @Description:(日期比较，如果s>=e 返回true 否则返回false)
     * @author luguosui
     */
    public static boolean compareDate(String s, String e) {
        if (parseDate(s) == null || parseDate(e) == null) {
            return false;
        }
        return parseDate(s).getTime() >= parseDate(e).getTime();
    }

    /**
     * 格式化日期
     *
     * @return
     */
    public static Date parseDate(String date) {
        return parse(date, "yyyy-MM-dd");
    }

    /**
     * 格式化日期
     *
     * @return
     */
    public static Date parseTime(String date) {
        return parse(date, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 格式化日期
     *
     * @return
     */
    public static Date parse(String date, String pattern) {
        try {
            return DateUtils.parseDate(date, pattern);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 格式化日期
     *
     * @return
     */
    public static String format(Date date, String pattern) {
        return DateFormatUtils.format(date, pattern);
    }

    /**
     * 把日期转换为Timestamp
     *
     * @param date
     * @return
     */
    public static Timestamp format(Date date) {
        return new Timestamp(date.getTime());
    }

    /**
     * 校验日期是否合法
     *
     * @return
     */
    public static boolean isValidDate(String s) {
        return parse(s, "yyyy-MM-dd HH:mm:ss") != null;
    }

    /**
     * 校验日期是否合法
     *
     * @return
     */
    public static boolean isValidDate(String s, String pattern) {
        return parse(s, pattern) != null;
    }

    public static int getDiffYear(String startTime, String endTime) {
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        try {
            int years = (int) (((fmt.parse(endTime).getTime() - fmt.parse(
                    startTime).getTime()) / (1000 * 60 * 60 * 24)) / 365);
            return years;
        } catch (Exception e) {
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            return 0;
        }
    }

    /**
     * <li>功能描述：时间相减得到天数
     *
     * @param beginDateStr
     * @param endDateStr
     * @return long
     * @author Administrator
     */
    public static long getDaySub(String beginDateStr, String endDateStr) {
        long day = 0;
        SimpleDateFormat format = new SimpleDateFormat(
                "yyyy-MM-dd");
        Date beginDate = null;
        Date endDate = null;

        try {
            beginDate = format.parse(beginDateStr);
            endDate = format.parse(endDateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000);
        // System.out.println("相隔的天数="+day);

        return day;
    }

    /**
     * 得到n天之后的日期
     *
     * @param days
     * @return
     */
    public static String getAfterDayDate(String days) {
        int daysInt = Integer.parseInt(days);

        Calendar canlendar = Calendar.getInstance(); // java.util包
        canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
        Date date = canlendar.getTime();

        SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sdfd.format(date);

        return dateStr;
    }

    /**
     * 得到n天之后是周几
     *
     * @param days
     * @return
     */
    public static String getAfterDayWeek(String days) {
        int daysInt = Integer.parseInt(days);

        Calendar canlendar = Calendar.getInstance(); // java.util包
        canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
        Date date = canlendar.getTime();

        SimpleDateFormat sdf = new SimpleDateFormat("E");
        String dateStr = sdf.format(date);

        return dateStr;
    }


    public static final short DAY_OF_YEAR = 1;    // 年中天
    public static final short DAY_OF_MONTH = 2;    // 月中天
    public static final short DAY_OF_WEEK_OF_MONTH = 3;    // 月周中天
    public static final short DAY_OF_WEEK_OF_YEAR = 4;    // 年周中天

    public static Date addMonth(Date start, int offset) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        calendar.add(Calendar.MONTH, offset);
        return calendar.getTime();
    }

    public static Date addWeek(Date start, int offset) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        calendar.add(Calendar.WEEK_OF_YEAR, offset);
        return calendar.getTime();
    }

    public static Date addYear(Date start, int offset) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        calendar.add(Calendar.YEAR, offset);
        return calendar.getTime();
    }

    public static Date setTime(Date date, int hour, int minute, int seconds) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, seconds);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * @param date    要格式化的时间
     * @param formart 时间格式化
     * @description 时间转字符串
     * @author qinj
     * @since 2017/12/22 17:16
     */
    public static String date2String(Date date, String formart) {
        if (StringUtils.isBlank(formart)) {
            throw new RuntimeException("时间格式不能为空!");
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minter = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        String dateString = formart.replaceAll("y+", number2String(year, false));
        dateString = dateString.replaceAll("M+", number2String(month, true));
        dateString = dateString.replaceAll("d+", number2String(day, true));
        dateString = dateString.replaceAll("H+", number2String(hour, true));
        dateString = dateString.replaceAll("m+", number2String(minter, true));
        dateString = dateString.replaceAll("s+", number2String(second, true));
        return dateString;
    }

    /**
     * @param date 要初始化的时间
     * @description 初始化时间，清除时分秒
     * @author qinj
     * @since 2017/12/22 17:32
     */
    public static Date initDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * @description 获取当月的最后一天
     * @author qinj
     * @since 2017/12/22 17:34
     */
    public static Date getLastDay(Date date, short type) {
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);    // 周一作为一周的第一天
        calendar.setTime(date);
        int lastDay = 1;
        switch (type) {
            case DAY_OF_YEAR:
                lastDay = calendar.getActualMaximum(Calendar.DAY_OF_YEAR);
                calendar.set(Calendar.DAY_OF_YEAR, lastDay);
                break;
            case DAY_OF_MONTH:
                lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                calendar.set(Calendar.DAY_OF_MONTH, lastDay);
                break;
//            case DAY_OF_WEEK_OF_MONTH :
//                System.out.println(calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
//                calendar.set(Calendar.DAY_OF_WEEK_IN_MONTH, Calendar.SUNDAY);
//                break ;
            case DAY_OF_WEEK_OF_YEAR:
                calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
                break;
        }
        return calendar.getTime();
    }

    public static Date getFirstDay(Date date, short type) {
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);    // 周一作为一周的第一天
        calendar.setTime(date);
        int firstDay = 1;
        switch (type) {
            case DAY_OF_YEAR:
                firstDay = calendar.getActualMinimum(Calendar.DAY_OF_YEAR);
                calendar.set(Calendar.DAY_OF_YEAR, firstDay);
                break;
            case DAY_OF_MONTH:
                firstDay = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
                calendar.set(Calendar.DAY_OF_MONTH, firstDay);
                break;
            case DAY_OF_WEEK_OF_MONTH:
                return getWeekInMonthFirstDay(date);
            case DAY_OF_WEEK_OF_YEAR:
                calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
                break;
        }
        return calendar.getTime();
    }

    public static Date addDay(Date target, int offset) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(target);
        calendar.add(Calendar.DAY_OF_MONTH, offset);
        return calendar.getTime();
    }

    public static Date addHour(Date target, int offset) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(target);
        calendar.add(Calendar.HOUR_OF_DAY, offset);
        return calendar.getTime();
    }

    /**
     * @param start      开始时间
     * @param end        结束时间
     * @param sameDayDif 当start == end时，是否作为不同天
     * @param initDate   是否初始化时间，初始化时分秒
     * @description 计算天数差
     * @author qinj
     * @since 2019/1/10 18:21
     */
    public static int caluationDiffDay(Date start, Date end, boolean sameDayDif, boolean initDate) {
        if (initDate) {
            start = initDate(start);
            end = initDate(end);
        }
        if (start.compareTo(end) == 0) {
            if (sameDayDif) {
                return 1;
            } else {
                return 0;
            }
        }

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        int startYear = calendar.get(Calendar.YEAR);
        int startDay = calendar.get(Calendar.DAY_OF_MONTH);

        calendar.setTime(end);
        int endYear = calendar.get(Calendar.YEAR);

        if (startYear == endYear) {
            return caluationSameYearDiffDay(start, end, false);
        } else if (startYear < endYear) {
            int diff = 0;
            for (int year = startYear; year <= endYear; year++) {
                calendar.set(Calendar.YEAR, year);
                if (year == startYear) {
                    diff += calendar.getActualMaximum(Calendar.DAY_OF_YEAR) - startDay;
                } else if (year < endYear) {
                    diff += calendar.getActualMaximum(Calendar.DAY_OF_YEAR);
                } else {
                    calendar.set(Calendar.MONTH, Calendar.JANUARY);
                    calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
                    diff += caluationSameYearDiffDay(calendar.getTime(), end, true);
                }
            }
            return diff;
        }

        return (int) ((end.getTime() - start.getTime()) / 1000 / 3600 / 24);
    }

    private static int caluationSameYearDiffDay(Date start, Date end, boolean newYear) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        int year = calendar.get(Calendar.YEAR);
        int startMonth = calendar.get(Calendar.MONTH);
        int startDay = calendar.get(Calendar.DAY_OF_MONTH);

        calendar.setTime(end);
        int endMonth = calendar.get(Calendar.MONTH);
        int endDay = calendar.get(Calendar.DAY_OF_MONTH);
        if (startMonth == endMonth) {
            // 同月
            if (newYear) {
                return endDay - startDay + 1;
            }
            return endDay - startDay;
        } else {
            // 不同月
            int diff = 0;
            for (int month = startMonth; month <= endMonth; month++) {
                calendar = Calendar.getInstance();
                calendar.set(Calendar.YEAR, year);
                calendar.set(Calendar.MONTH, month);
                int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                if (month == startMonth) {
                    if (newYear) {
                        diff += maxDay - startDay + 1;
                    } else
                        diff += maxDay - startDay;
                } else if (month == endMonth) {
//                    if(newYear)
//                        diff += endDay + 1;
//                    else
                    diff += endDay;
                } else {
                    diff += maxDay;
                }
            }
            return diff;
        }
    }

    /**
     * @description 获取周第一天
     * @author qinj
     * @since 2019/3/5 14:50
     */
    public static Date getWeekInMonthFirstDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        int weekInMonth = calendar.get(Calendar.WEEK_OF_MONTH);
        if (weekInMonth == 1) {
            // 月中第一周，取第一天
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            return calendar.getTime();
        }
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        return calendar.getTime();
    }

    /**
     * @description 获取周最后一天
     * @author qinj
     * @since 2019/3/5 14:50
     */
    public static Date getWeekInMonthLastDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        int weekInMonth = calendar.get(Calendar.WEEK_OF_MONTH);
        int maxWeekInMonth = calendar.getActualMaximum(Calendar.WEEK_OF_MONTH);
        if (weekInMonth == maxWeekInMonth) {
            // 月中最后一周，取月最后一天
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            return calendar.getTime();
        }
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        return calendar.getTime();
    }

    private static String number2String(Number number, boolean fillZero) {
        StringBuilder builder = new StringBuilder();
        if (number.intValue() < 10 && fillZero)
            builder.append(0);
        builder.append(number);
        return builder.toString();
    }


    /**
     * @description 获取年第一天
     * @author qinj
     * @since 2019/3/5 14:50
     */
    public static Date getYeasFirstDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int currentYear = calendar.get(Calendar.YEAR);
        calendar.clear();
        calendar.set(Calendar.YEAR, currentYear);
        Date currYearFirst = calendar.getTime();
        return currYearFirst;

    }


}
